<template>
  <div>
    <!-- 添加和编辑共用的弹出表单 -->
    <el-dialog :title="formTitle" :visible.sync="dialogFormVisible" width="500px" >
      <el-form :model="item" >
        <el-form-item label="用户名" :label-width="formLabelWidth" >
          <el-input v-model='item.dsUserName' style="width: 200px"  @blur="shiqu" ></el-input>
          <span style="color: red">{{mag}}</span>
        </el-form-item>
        <el-form-item label="密码" :label-width="formLabelWidth" v-if="formPassword">
          <el-input v-model="item.dsUserPassword" show-password style="width: 200px" ></el-input>
        </el-form-item>
        <el-form-item label="手机号" :label-width="formLabelWidth">
          <el-input v-model='item.dsUserTel' style="width: 200px" @blur="phone"></el-input>
          <span style="color: red">{{mag1}}</span>
        </el-form-item>
        <el-form-item label="邮箱" :label-width="formLabelWidth" >
          <el-input v-model="item.dsUserEmail" style="width: 200px" @blur="mailbox"></el-input>
          <span style="color: red">{{mag2}}</span>
        </el-form-item>
        <el-form-item label="权限" :label-width="formLabelWidth">
          <el-select v-model="item.dsUserRole" placeholder="--请选择权限--">
            <el-option v-for="(role, index) in roles" :value="index" :key="index" :label="role"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="editHandler()">确 定</el-button>
      </div>
    </el-dialog>

    <div>
      <el-input style="width: 200px" suffix-icon="el-icon-search" v-model="searchValue"/>
      <el-button class="ml-15" type="primary" @click="searchUserByName(searchValue)">搜索</el-button>
      <el-button class="ml-15" type="success" @click="searchUserByName('')">显示全部</el-button>
    </div>

    <div style="margin: 10px 0">
      <el-button type="danger" @click="removeAll()">删除选中<i class="el-icon-remove-outline"></i></el-button>
      <el-button type="primary" @click="add()">添加用户<i class="el-icon-circle-plus-outline"></i></el-button>
    </div>

    <el-table
        ref="multipleTable"
        :data="tableData"
        border
        style="width: 100%">
      <el-table-column
          type="selection"
          width="55">
      </el-table-column>
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="用户名">
              <span>{{ props.row.dsUserName }}</span>
            </el-form-item>
            <el-form-item label="手机号">
              <span>{{ props.row.dsUserTel }}</span>
            </el-form-item>
            <el-form-item label="邮箱">
              <span>{{ props.row.dsUserEmail }}</span>
            </el-form-item>
            <el-form-item label="用户ID">
              <span>{{ props.row.dsUserId }}</span>
            </el-form-item>
            <el-form-item label="用户权限">
              <span>{{ props.row.dsUserRole === 1 ? '管理员' : '普通用户' }}</span>
            </el-form-item>
            <el-form-item label="创建时间">
              <span>{{ props.row.createTime?new Date(props.row.createTime).toLocaleString(): null }}</span>
            </el-form-item>
            <el-form-item label="近一次修改">
              <span>{{ props.row.modifyTime?new Date(props.row.modifyTime).toLocaleString(): '未修改'}}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column
          label="用户ID"
          prop="dsUserId">
      </el-table-column>
      <el-table-column
          label="用户名"
          prop="dsUserName">
      </el-table-column>
      <el-table-column
          label="用户权限"
      >
        <template slot-scope="scope">
          {{ scope.row.dsUserRole === 1 ? '管理员' : '普通用户'}}
        </template>
      </el-table-column>
      <el-table-column
          label="操作">
        <template slot-scope="scope">
          <el-button type="warning" @click="edit(scope.row)">编辑<i class="el-icon-edit"></i> </el-button>
          <el-button type="danger" @click="remove(scope.row)">删除 <i class="el-icon-remove-outline"></i></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页功能 -->
    <div>
      <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[5, 10, 15, 20]"
          :page-size="pageSize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="pageTotal">
      </el-pagination>
    </div>
  </div>
</template>

<script>

export default {
  name: "UserTableView",
  data() {
    return {
      item: {
        description: null,
        createTime: null,
        deleted: null,
        dsUserEmail: null,
        dsUserId:null,
        dsUserName:null,
        dsUserPassword:null,
        dsUserRole:null,
        dsUserTel:null,
        modifyTime:null
      },
      tableData: [
        this.item
      ],
      pageSize:5,
      pageTotal: 0,
      currentPage: 1,
      searchValue: '',
      formTitle: null,
      dialogFormVisible: false,
      formLabelWidth: '120px',
      roles: [
          '普通用户',
          '管理员'
      ],
      formPassword: false,
      mag:"",
      mag1:"",
      mag2:"",
      active:null,
    }
  },
  methods: {
    selectCurrentPageUser: function (page, pageSize, name) {
      this.api.userApi.selectUserPage(page, pageSize, name)
      .then((response) => {
        this.tableData = response[0]
        this.pageTotal = response[1]
      })
      .catch((error) => {
        this.tableData = error
      })
    },

    searchUserByName: function (name) {
      this.currentPage = 1
      this.selectCurrentPageUser(this.currentPage, this.pageSize, name)
    },

    editHandler: function () {
      if (this.item.dsUserId == null) {
        this.addUser(this.item)
      } else {
        this.editUser(this.item)
      }
    },

    addUser: function (data) {
      this.api.userApi.addUser(data)
          .then(res => {
            if (res) {
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success'
              })
            } else {
              this.$notify.error({
                title: '失败'
              })
            }
            this.selectCurrentPageUser(this.currentPage, this.pageSize, '')
          })
          .catch(err => {
            console.log(err)
            this.$notify.error({
              title: '失败',
              message: '信息：' + err
            })
          })
      this.dialogFormVisible = false
    },

    editUser: function (data) {
      this.api.userApi.updateUser(data)
          .then(res => {
            if (res) {
              this.$notify({
                title: '成功',
                message: '第' + data.dsUserId + '个用户修改成功',
                type: 'success'
              })
            } else {
              this.$notify.error({

                title: '失败'
              })
            }
            this.selectCurrentPageUser(this.currentPage, this.pageSize, this.searchValue)
          })
          .catch(err => {
            console.log(err)
            this.$notify.error({
              title: '失败',
              message: '信息：' + err
            })
          })
      this.dialogFormVisible = false
    },

    deleteUser: function (data) {

      this.api.userApi.deleteUser(data)
          .then((res) => {
            if (res) {
              this.$notify({
                title: '成功',
                message: '第' + data.dsUserId + '个用户修改成功',
                type: 'success'
              })
              this.selectCurrentPageUser(this.currentPage, this.pageSize, this.searchValue)
            } else {
              this.$notify.error({
                title: '失败'
              })
            }
          })
          .catch(err => {
            console.log(err)
            this.$notify.error({
              title: '失败',
              message: '信息：' + err
            })
          })
    },

    handleSizeChange(pageSize) {
      this.pageSize = pageSize
      this.selectCurrentPageUser(this.currentPage, pageSize, this.searchValue)
    },

    handleCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.selectCurrentPageUser(currentPage, this.pageSize, this.searchValue)
    },

    add: function () {
      this.item = {
        description: null,
        createTime: null,
        deleted: null,
        dsUserEmail: null,
        dsUserId: null,
        dsUserName: null,
        dsUserPassword: null,
        dsUserRole: null,
        dsUserTel: null,
        modifyTime: null
      }
      this.formTitle = '添加用户'
      this.formPassword = true
      this.dialogFormVisible = true
    },

    edit: function (data) {
      this.item = data
      this.formTitle = '编辑用户'
      this.formPassword = false
      this.dialogFormVisible = true
    },

    remove: function (data) {
      console.log(data)
      this.$confirm('此操作将删除用户, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.deleteUser(data)
        this.$message({
          type:'warning',
          message:'该用户为管理员，不能进行删除！'
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消操作'
        });
      });
    },
    shiqu()
    {
      this.api.userApi.verification(this.item.dsUserName).then(res=>
      {
        this.mag=res.mag;
      })
    },

    mailbox()
    {
      if(this.item.dsUserEmail===null||this.item.dsUserEmail==="")
      {
        this.mag2="邮箱不能为空"
      }else
      {
        let reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
        if(reg.test(this.item.dsUserEmail))
        {
          this.mag2=""
        }
        else
        {
          this.mag2="邮箱格式不正确"
        }
      }
    },
    phone()
    {
      if(this.item.dsUserTel===null||this.item.dsUserTel==="")
      {
        this.mag1="手机号不能为空"
      }else
      {
        let reg=/^[1][3,4,5,6,7,8,9][0-9]{9}$/;
        if(reg.test(this.item.dsUserTel))
        {
          this.mag1=""
        }
        else
        {
          this.mag1="手机号格式不正确"
        }
      }
    },
    removeAll()
    {
        this.$confirm('此操作将删除用户, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          let ids=[];
          for (const i in this.$refs.multipleTable.selection) {
            ids.push(this.$refs.multipleTable.selection[i].dsUserId)
          }
          this.api.userApi.deleteAll(ids).then((res) => {
            if (res) {
              this.$notify({
                title: '成功',
                message: '有' + ids.length + '个设备删除成功',
                type: 'success'
              })
              this.selectCurrentPageUser(this.currentPage, this.pageSize, this.searchValue)
            } else {
              this.$notify.error({
                title: '失败'
              })
            }
          }).catch(err => {
                console.log(err)
                this.$notify.error({
                  title: '失败',
                  message: '信息：' + err
                })
              })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          });
        });
    }
  },

  mounted() {
    this.selectCurrentPageUser(this.currentPage, this.pageSize, this.searchValue)
  },
}
</script>

<style scoped>


</style>
